package cn.fastpay.management.controller;

import cn.fastpay.core.vo.PageVO;
import cn.fastpay.management.entity.PermissionMenu;
import cn.fastpay.management.entity.PermissionRole;
import cn.fastpay.management.service.PermissionMenuService;
import cn.fastpay.management.service.PermissionRoleService;
import cn.fastpay.core.vo.ApiCommonResultVO;
import cn.fastpay.core.vo.ApiPageListResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author freewolf
 */
@RestController
@RequestMapping(value = "/api/menu")
public class PermissionMenuController {

    @Autowired
    private PermissionMenuService permissionMenuService;
    @Autowired
    private PermissionRoleService permissionRoleService;

    @PostMapping("/all")
    private ApiPageListResultVO page() {
        List<PermissionMenu> menuList = this.permissionMenuService.getAll();
        PageVO page = new PageVO(menuList.size(), 0, 0, menuList);
        return new ApiPageListResultVO(page);
    }

    @PostMapping("/add")
    private ApiCommonResultVO add(@RequestBody PermissionMenu menu) {
        if (menu.getId() == null) {
            PermissionMenu parentMenu = this.permissionMenuService.getById(menu.getParent().getId());
            menu.setParent(parentMenu);
            this.permissionMenuService.add(menu);
        }
        return ApiCommonResultVO.success();
    }

    @PostMapping("/update")
    private ApiCommonResultVO update(@RequestBody PermissionMenu menu) {
        if (menu.getId() != null) {
            PermissionMenu parentMenu;
            if (menu.getParent().getId() != null) {
                parentMenu = this.permissionMenuService.getById(menu.getParent().getId());
                menu.setParent(parentMenu);
            } else {
                menu.setParent(null);
            }
            this.permissionMenuService.update(menu);
        }

        return ApiCommonResultVO.success();
    }

    @PostMapping("/remove")
    private ApiCommonResultVO remove(@RequestBody PermissionMenu menu) {
        PermissionMenu removeMenu = this.permissionMenuService.getById(menu.getId());
        for (PermissionRole role : removeMenu.getRoleSet()) {
            role.getMenuSet().remove(removeMenu);
            this.permissionRoleService.update(role);
        }
        this.permissionMenuService.deleteById(menu.getId());
        return ApiCommonResultVO.success();
    }

}
